import { fetchData } from '.';
import * as cheerio from 'cheerio';
export async function scrapePoetId(url: string): Promise<string[]> {
  try {
    const html: string | Buffer = await fetchData(url);
    if (html) {
      const $ = cheerio.load(html);

      const results = [];
      const mainElement = $('.m-auto.grid.grid-cols-1.gap-4.p-4'); // 获取目标节点
      mainElement.children('div').each((index, element) => {
        const resurl = $(element).find('a').attr('href'); // 获取h2内容
        results.push(resurl); // 添加到结果数组
      });

      // eslint-disable-next-line @typescript-eslint/no-unsafe-return
      return results;
    }
  } catch (error) {
    throw Error(error);
  }
}

export async function scrapePoet(url: string) {
  try {
    const html: string | Buffer = await fetchData(url);
    if (html) {
      const $ = cheerio.load(html);
      const container = $(
        'header.rounded-box.m-auto.flex.max-w-screen-sm.px-4.py-8',
      );
      const poetName = $('h1[prose-h1]').find('span').eq(0).text().trim();

      const description = $('p.mt-4.text-f100.text-secondary-foreground')
        .text()
        .trim(); // 获取简介
      let birthday = '';
      let deadday = '';
      let wiki = '';
      container.children('div').each((index, element) => {
        console.log(index);
        const target = $(element).children().eq(2);
        const date = target.children().eq(0).find('span');
        console.log(date.length);
        birthday = date.find('span.text-f50').eq(0).text().trim();
        deadday = date.find('span.text-f50').eq(1).text().trim();
        wiki = target.children().eq(1).find('a').attr('href'); // 获取维基百科链接
      });
      return {
        name: poetName,
        description,
        birthday: birthday === '?' ? null : birthday,
        deadday: deadday === '?' ? null : deadday,
        wiki,
        outerurl: url,
      };
    }
  } catch (error) {
    console.log(error);
  }
}
